#include "app_buffer.h"
#include <stdlib.h>
#include <string.h>
#include "log/log.h"

Buffer *app_buffer_init(int size){
    Buffer *buffer = (Buffer *)malloc(sizeof(Buffer));
    buffer->sub_buffer[0] = (Sub_buffer *)malloc(sizeof(Sub_buffer));
    buffer->sub_buffer[1] = (Sub_buffer *)malloc(sizeof(Sub_buffer));
    buffer->sub_buffer[0]->ptr = (unsigned char*)malloc(size);
    buffer->sub_buffer[1]->ptr = (unsigned char*)malloc(size);
    buffer->sub_buffer[0]->len = 0;
    buffer->sub_buffer[1]->len = 0;
    buffer->sub_buffer[0]->size = size;
    buffer->sub_buffer[1]->size = size;
    buffer->read_index = 0;
    buffer->write_index = 1;
    pthread_mutex_init(&buffer->write_lock,NULL);
    pthread_mutex_init(&buffer->read_lock,NULL);
    return buffer;
}

void app_buffer_free(Buffer *buffer){
    free(buffer->sub_buffer[0]->ptr);
    free(buffer->sub_buffer[1]->ptr);
    free(buffer->sub_buffer[0]);
    free(buffer->sub_buffer[1]);
    free(buffer);
}

int app_buffer_write(Buffer *buffer,char *data,int len){
    //因为一个字节存储长度，所以要判断len长度是否小于2555
    if (len > 255)
    {
        log_debug("data len is too long");
        return -1;
    }
    pthread_mutex_lock(&buffer->write_lock);
    //获取当前的写缓存区
    Sub_buffer *w_buffer = buffer->sub_buffer[buffer->write_index];

    //判断当前缓存区是否还有足够的空间
    if (w_buffer->len + len > w_buffer->size)
    {
        log_debug("write_buffer is full");
        pthread_mutex_unlock(&buffer->write_lock);
        return -1;
    }
    //将数据写入缓存区
    w_buffer->ptr[w_buffer->len] = len;
    memcpy(w_buffer->ptr+w_buffer->len+1,data,len);
    w_buffer->len += len+1;
    pthread_mutex_unlock(&buffer->write_lock);
    return 0;
    
}
static void buffer_swap(Buffer *buffer){
    pthread_mutex_lock(&buffer->write_lock);
    int temp = buffer->read_index;
    buffer->read_index = buffer->write_index;
    buffer->write_index = temp;
    pthread_mutex_unlock(&buffer->write_lock);
}

int app_buffer_read(Buffer *buffer,char *data,int size){
    pthread_mutex_lock(&buffer->read_lock);
    //获取当前的读缓存区
    Sub_buffer *r_buffer = buffer->sub_buffer[buffer->read_index];
    //判断当前缓存区是否还有数据
    if (r_buffer->len == 0){
        buffer_swap(buffer);
        r_buffer = buffer->sub_buffer[buffer->read_index];
        if (r_buffer->len == 0){
            {
                log_debug("buffer is empty");
                pthread_mutex_unlock(&buffer->read_lock);
                return -1;
            }
        
        }
    }


    //获取当前缓存区的数据长度
    int len = r_buffer->ptr[0];
        //判断当前读取的数据是否大于size
    if (len > size){
        log_debug("data len is too long");
        pthread_mutex_unlock(&buffer->read_lock);
        return -1;
    }
    //获取缓存区的数据
    memcpy(data,r_buffer->ptr+1,len);
    //将缓存区的数据前移
    memmove(r_buffer->ptr,r_buffer->ptr+len+1,r_buffer->len-len-1);
    r_buffer->len -= len+1;
    pthread_mutex_unlock(&buffer->read_lock);
    return len;
}